package com.liehu.business.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("测试---通过拦截器--JwtInterceptor");

        //无论如何都放行。具体能不能操作还是在具体的操作中去判断
        //拦截器只是负责把头请求中包含token的令牌进行一个验证解析

        String header =  request.getHeader("Authorization");



        if (header != null && !"".equals(header)){

            System.out.println("header:+++++"+header);
            //如果包含有Authorization信息，就对其进行解析
            if (header.startsWith("liehuManagedByCyberX ")){ // Be ar er
                //得到token
                String token = header.substring(21);//截取21位字符后的真实token信息
                System.out.println("token++++:"+token);

                //对令牌进行验证
                try {

                    Claims claims =  jwtUtil.parseJWT(token); //解析令牌
                    String roles = (String) claims.get("roles");//获取该token的角色信息
                    System.out.println("roles:"+roles);
                    if (roles != null && roles.equals("admin")){

                        request.setAttribute("claims_admin",claims);

                    }
                    if (roles != null && roles.equals("customer")){

                        request.setAttribute("claims_customer",claims);

                    }
                    if (roles != null && roles.equals("employee")){

                        request.setAttribute("claims_employee",claims);

                    }

                }catch (Exception e){

                    throw  new RuntimeException("令牌不正确！");


                }
            }

        }

        return true;
    }
}
